<template>
  <div class="result-container">
    <el-card class="result-header-card">
      <div slot="header" class="card-header">
        <span>测评结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      <div class="task-info">
        <span class="task-title">{{ taskInfo.taskName || '未知测评任务' }}</span>
        <el-tag type="success" v-if="taskInfo.status === 'completed'">已完成</el-tag>
        <el-tag type="warning" v-else-if="taskInfo.status === 'expired'">已过期</el-tag>
        <el-tag type="info" v-else>{{ taskInfo.status || '未知状态' }}</el-tag>
        <span class="task-time">测评时间: {{ taskInfo.submitTime || '未知' }}</span>
      </div>
    </el-card>

    <div class="result-content">
      <!-- 左侧区域选择 -->
      <div class="result-sidebar">
        <el-card shadow="hover">
          <div slot="header">
            <span>量表项目</span>
          </div>
          <el-menu
            :default-active="activeScaleId"
            class="result-menu"
            @select="handleScaleSelect">
            <el-menu-item v-for="scale in scaleList" :key="scale.id" :index="scale.id">
              <i :class="scale.icon || 'el-icon-document'"></i>
              <span slot="title">{{ scale.name }}</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </div>

      <!-- 右侧内容区 -->
      <div class="result-main">
        <!-- 用户信息卡片 -->
        <el-card class="user-profile-card" shadow="hover" v-if="userInfo.userId">
          <div class="user-profile-header">
            <div class="avatar-container">
              <div class="avatar-placeholder">{{ userInfo.userName ? userInfo.userName.substr(0, 1).toUpperCase() : 'U' }}</div>
            </div>
            <div class="user-basic-info">
              <h3 class="user-name">{{ userInfo.userName }}</h3>
              <p class="user-role">{{ userInfo.roles && userInfo.roles.length > 0 ? userInfo.roles[0].roleName : '' }}</p>
            </div>
          </div>
          <div class="user-profile-details">
            <div class="info-item">
              <div class="info-label"><i class="el-icon-user"></i> 昵称：</div>
              <div class="info-value">{{ userInfo.nickName }}</div>
            </div>
            <div class="info-item">
              <div class="info-label"><i class="el-icon-male"></i> 性别：</div>
              <div class="info-value">{{ userInfo.sex === '0' ? '男' : '女' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label"><i class="el-icon-message"></i> 邮箱：</div>
              <div class="info-value">{{ userInfo.email || '暂无' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label"><i class="el-icon-school"></i> 班级：</div>
              <div class="info-value">{{ userInfo.dept ? userInfo.dept.deptName : '暂无' }}</div>
            </div>
          </div>
        </el-card>

        <!-- 结果内容 -->
        <el-card class="result-detail-card" shadow="hover">
          <div slot="header">
            <span>{{ currentScale.name || '测评结果' }}</span>
          </div>
          
          <!-- 结果总览 -->
          <div class="result-summary" v-if="currentResult">
            <h3>测评结论</h3>
            <div class="conclusion-box">
              <div class="level-tag">
                <el-tag :type="getLevelTagType(currentResult.level)">{{ currentResult.level }}</el-tag>
              </div>
              <div class="conclusion-content">
                {{ currentResult.conclusion || '暂无结论' }}
              </div>
            </div>
            
            <div class="result-scores">
              <h4>得分情况</h4>
              <el-progress 
                :percentage="currentResult.percentScore" 
                :color="getScoreColor(currentResult.percentScore)"
                :format="format => `${currentResult.score || 0}分/${currentResult.totalScore || 100}分`"
                :stroke-width="18">
              </el-progress>
            </div>

            <div class="result-description">
              <h4>结果说明</h4>
              <p>{{ currentResult.description || '暂无结果说明' }}</p>
            </div>
          </div>
          
          <!-- 答题详情 -->
          <div class="question-answers" v-if="currentScale.questions && currentScale.questions.length > 0">
            <h3>答题详情</h3>
            <div 
              v-for="(question, qIndex) in currentScale.questions" 
              :key="qIndex" 
              class="question-item"
            >
              <div class="question-title">
                <span class="question-number">{{ qIndex + 1 }}.</span>
                <span>{{ question.title }}</span>
                <span class="question-type" v-if="question.type === 'single'">[单选题]</span>
                <span class="question-type" v-else-if="question.type === 'multiple'">[多选题]</span>
                <span class="question-type" v-else-if="question.type === 'text'">[问答题]</span>
                <span class="question-type" v-else-if="question.type === 'rate'">[评分题]</span>
              </div>
              
              <div class="question-answer">
                <template v-if="question.type === 'single'">
                  <div class="answer-content">
                    <i class="el-icon-check"></i>
                    {{ getOptionLabel(question, question.answer) }}
                  </div>
                </template>
                
                <template v-else-if="question.type === 'multiple'">
                  <div v-for="(answer, aIndex) in question.answer" :key="aIndex" class="answer-content">
                    <i class="el-icon-check"></i>
                    {{ getOptionLabel(question, answer) }}
                  </div>
                </template>
                
                <template v-else-if="question.type === 'text'">
                  <div class="answer-content text-answer">
                    {{ question.answer || '未填写' }}
                  </div>
                </template>
                
                <template v-else-if="question.type === 'rate'">
                  <div class="answer-content">
                    <el-rate
                      v-model="question.answer"
                      disabled
                      show-score
                      text-color="#ff9900">
                    </el-rate>
                  </div>
                </template>
              </div>
            </div>
          </div>
          
          <div class="no-result" v-if="!currentResult && (!currentScale.questions || currentScale.questions.length === 0)">
            <i class="el-icon-warning-outline"></i>
            <p>暂无测评结果数据</p>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getAssess } from "@/api/system/assess"
import { getUserProfile } from "@/api/system/user"

export default {
  name: "ResultView",
  data() {
    return {
      taskId: null,
      loading: false,
      userInfo: {},
      taskInfo: {},
      scaleList: [],
      activeScaleId: '',
      currentScale: {},
      resultData: {}
    }
  },
  computed: {
    currentResult() {
      if (!this.activeScaleId || !this.resultData) return null;
      return this.resultData[this.activeScaleId] || null;
    }
  },
  created() {
    this.taskId = this.$route.query.taskId;
    if (this.taskId) {
      this.getTaskInfo();
      this.getUserInfo();
    } else {
      this.$message.error('任务ID不能为空');
      this.goBack();
    }
  },
  methods: {
    // 获取任务信息
    getTaskInfo() {
      this.loading = true;
      getAssess(this.taskId).then(response => {
        if (response.code === 200 && response.data) {
          this.taskInfo = response.data;
          
          // 解析量表信息
          if (this.taskInfo.scaleIdList && Array.isArray(this.taskInfo.scaleIdList)) {
            this.processScaleList(this.taskInfo.scaleIdList);
          } else if (typeof this.taskInfo.scaleIds === 'string') {
            try {
              const scaleIds = JSON.parse(this.taskInfo.scaleIds);
              this.processScaleList(scaleIds);
            } catch (e) {
              console.error('解析量表IDs失败', e);
            }
          }
          
          // 模拟结果数据（实际项目中应从后端获取）
          this.mockResultData();
        } else {
          this.$message.error('获取任务信息失败');
        }
        this.loading = false;
      }).catch(err => {
        console.error('获取任务信息出错', err);
        this.$message.error('获取任务信息出错');
        this.loading = false;
      });
    },
    
    // 处理量表列表
    processScaleList(scaleIds) {
      if (!scaleIds || !Array.isArray(scaleIds) || scaleIds.length === 0) return;
      
      // 模拟量表数据（实际项目中应从后端获取详细信息）
      this.scaleList = scaleIds.map((id, index) => {
        const name = `量表 ${index + 1}`;
        const icons = ['el-icon-document', 'el-icon-notebook-1', 'el-icon-tickets', 'el-icon-reading'];
        return {
          id: id,
          name: name,
          icon: icons[index % icons.length],
          questions: this.mockQuestions(id)
        };
      });
      
      if (this.scaleList.length > 0) {
        this.activeScaleId = this.scaleList[0].id;
        this.currentScale = this.scaleList[0];
      }
    },
    
    // 获取用户信息
    getUserInfo() {
      getUserProfile().then(res => {
        if (res.code === 200 && res.data) {
          this.userInfo = res.data;
        }
      }).catch(err => {
        console.error('获取用户信息失败', err);
      });
    },
    
    // 处理量表选择
    handleScaleSelect(id) {
      this.activeScaleId = id;
      this.currentScale = this.scaleList.find(scale => scale.id === id) || {};
    },
    
    // 返回列表
    goBack() {
      this.$router.push('/scale/ping');
    },
    
    // 获取选项标签
    getOptionLabel(question, value) {
      if (!question || !question.options) return '未知选项';
      const option = question.options.find(opt => opt.value === value);
      return option ? option.label : '未知选项';
    },
    
    // 获取等级标签类型
    getLevelTagType(level) {
      const levelMap = {
        '正常': 'success',
        '轻度': 'warning',
        '中度': 'danger',
        '重度': 'danger'
      };
      return levelMap[level] || 'info';
    },
    
    // 获取得分颜色
    getScoreColor(percent) {
      if (percent < 30) return '#67C23A';  // 绿色 - 正常
      if (percent < 60) return '#E6A23C';  // 黄色 - 轻度
      if (percent < 80) return '#F56C6C';  // 红色 - 中度
      return '#F56C6C';                    // 红色 - 重度
    },
    
    // 模拟问题数据
    mockQuestions(scaleId) {
      // 这里模拟问题数据，实际项目中应从后端获取
      const types = ['single', 'multiple', 'text', 'rate'];
      const count = 5 + Math.floor(Math.random() * 5); // 5-9个问题
      
      return Array.from({ length: count }).map((_, index) => {
        const type = types[Math.floor(Math.random() * types.length)];
        const question = {
          id: `q${index+1}`,
          title: `问题 ${index+1}：这是一个${type === 'single' ? '单选' : type === 'multiple' ? '多选' : type === 'text' ? '问答' : '评分'}类型的问题`,
          type: type
        };
        
        // 根据类型添加选项和答案
        if (type === 'single' || type === 'multiple') {
          question.options = [
            { label: '选项A', value: 'A' },
            { label: '选项B', value: 'B' },
            { label: '选项C', value: 'C' },
            { label: '选项D', value: 'D' }
          ];
          
          if (type === 'single') {
            question.answer = ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)];
          } else {
            const count = 1 + Math.floor(Math.random() * 3); // 1-3个选项
            const options = ['A', 'B', 'C', 'D'];
            question.answer = Array.from({ length: count }).map(() => 
              options.splice(Math.floor(Math.random() * options.length), 1)[0]
            );
          }
        } else if (type === 'text') {
          question.answer = '这是一个文本回答示例，实际项目中应从用户提交的答案中获取。';
        } else if (type === 'rate') {
          question.answer = 1 + Math.floor(Math.random() * 5); // 1-5星
        }
        
        return question;
      });
    },
    
    // 模拟结果数据
    mockResultData() {
      // 这里模拟结果数据，实际项目中应从后端获取
      this.resultData = {};
      
      // 为每个量表创建一个结果
      this.scaleList.forEach(scale => {
        const levelOptions = ['正常', '轻度', '中度', '重度'];
        const level = levelOptions[Math.floor(Math.random() * levelOptions.length)];
        const score = 20 + Math.floor(Math.random() * 80); // 20-99分
        const totalScore = 100;
        
        this.resultData[scale.id] = {
          level: level,
          score: score,
          totalScore: totalScore,
          percentScore: Math.round((score / totalScore) * 100),
          conclusion: `根据测评结果，您在${scale.name}维度表现为${level}水平。`,
          description: `该维度测量了您的心理健康状况的重要方面。您的得分为${score}分（总分${totalScore}分），处于${level}水平。${
            level === '正常' ? '表明您在这方面保持健康状态，建议继续保持良好的生活和学习习惯。' :
            level === '轻度' ? '表明您可能存在轻微的问题，建议适当调整生活习惯，增加运动和社交活动。' :
            level === '中度' ? '表明您需要关注这方面的问题，建议咨询专业心理老师获取帮助。' :
            '表明您在这方面存在较严重的问题，强烈建议尽快寻求专业心理医生的帮助。'
          }`
        };
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.result-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.result-header-card {
  margin-bottom: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .task-info {
    display: flex;
    align-items: center;
    gap: 15px;
    
    .task-title {
      font-size: 16px;
      font-weight: 500;
    }
    
    .task-time {
      color: #909399;
      font-size: 14px;
    }
  }
}

.result-content {
  display: flex;
  gap: 20px;
  
  .result-sidebar {
    width: 250px;
    flex-shrink: 0;
    
    .el-card {
      margin-bottom: 0;
    }
    
    .result-menu {
      border-right: none;
    }
  }
  
  .result-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
}

/* 用户信息卡片样式 */
.user-profile-card {
  margin-bottom: 0;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.user-profile-header {
  padding: 20px;
  background: linear-gradient(135deg, #409EFF 0%, #64b5f6 100%);
  color: white;
  display: flex;
  align-items: center;
}

.avatar-container {
  margin-right: 20px;
}

.avatar-placeholder {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: white;
  color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.user-basic-info {
  flex: 1;
}

.user-name {
  margin: 0 0 5px 0;
  font-size: 20px;
  font-weight: 500;
}

.user-role {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.user-profile-details {
  padding: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  border-bottom: 1px dashed #ebeef5;
  padding-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.info-label {
  width: 120px;
  color: #606266;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.info-label i {
  margin-right: 5px;
  font-size: 16px;
  color: #409EFF;
}

.info-value {
  flex: 1;
  color: #303133;
}

/* 结果详情卡片 */
.result-detail-card {
  .result-summary {
    margin-bottom: 30px;
    
    h3, h4 {
      margin-top: 0;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      color: #303133;
    }
    
    .conclusion-box {
      display: flex;
      align-items: flex-start;
      background-color: #f8f9fa;
      padding: 15px;
      border-radius: 6px;
      margin-bottom: 20px;
      
      .level-tag {
        margin-right: 15px;
        
        .el-tag {
          font-size: 14px;
          padding: 5px 10px;
        }
      }
      
      .conclusion-content {
        flex: 1;
        line-height: 1.6;
      }
    }
    
    .result-scores {
      margin-bottom: 20px;
      
      h4 {
        border-bottom: none;
        padding-bottom: 0;
      }
    }
    
    .result-description {
      p {
        line-height: 1.6;
        margin: 0;
        color: #606266;
      }
    }
  }
  
  .question-answers {
    h3 {
      margin-top: 0;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      color: #303133;
    }
    
    .question-item {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px dashed #ebeef5;
      
      &:last-child {
        margin-bottom: 0;
        padding-bottom: 0;
        border-bottom: none;
      }
      
      .question-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 15px;
        color: #303133;
        
        .question-number {
          font-weight: bold;
          margin-right: 10px;
          color: #409EFF;
        }
        
        .question-type {
          font-size: 14px;
          color: #909399;
          font-weight: normal;
          margin-left: 8px;
          background-color: #f0f5ff;
          padding: 2px 8px;
          border-radius: 4px;
        }
      }
      
      .question-answer {
        padding-left: 25px;
        
        .answer-content {
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          
          i {
            color: #67C23A;
            margin-right: 10px;
          }
          
          &.text-answer {
            background-color: #f8f9fa;
            padding: 10px 15px;
            border-radius: 4px;
            color: #606266;
            line-height: 1.6;
          }
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
  
  .no-result {
    text-align: center;
    padding: 40px 20px;
    color: #909399;
    
    i {
      font-size: 40px;
      margin-bottom: 10px;
    }
    
    p {
      margin: 0;
      font-size: 16px;
    }
  }
}

/* 响应式样式 */
@media (max-width: 992px) {
  .result-content {
    flex-direction: column;
    
    .result-sidebar {
      width: 100%;
      margin-bottom: 20px;
    }
  }
}
</style> 